<?php
namespace iBrand\Shop\Core\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use iBrand\Shop\Core\Models\Balance;

class BalanceRepository extends BaseRepository
{

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Balance::class;
    }

    /**
     * get user's balance
     *
     * @return int
     * */
    public function getSum($id, $type = null)
    {
        if ($type !== null) {
            $sum = $this->model->where([
                'user_id' => $id,
                'type' => $type
            ])->sum();
        } else {
            $sum = $this->model->where('user_id', $id)->sumBalance();
        }
        if ($sum) {
            return $this->getSumNumeric($sum);
        } else {
            return 0;
        }

    }

    public function fluctuation($user_id, $type = 'recharge')
    {
        return $this->model->where('user_id', $user_id)->where('type', $type);
    }

    public function addRecord($arr)
    {
        return $this->model->create($arr);
    }

    private function getSumNumeric($sum)
    {
        if (!is_numeric($sum)) {
            return 0;
        }
        return (int)$sum;
    }



    public function getShopOrder($user_id,$limit=15){
        return $this->model->where('user_id', $user_id)->where('type','shop_order_payment')
            ->with('payment.order')
            ->whereHas('payment.order', function ($query) use ($user_id) {
                return $query->where('user_id',$user_id);
            })->paginate($limit);

    }




}